﻿using System;
using System.Collections.Generic;

namespace FastMVVM.Core
{
    /// <summary>
    /// This is responsible for instanciate any ViewModel.
    /// With this you can manage through instanciate a new, or just get a singleton instance.
    /// </summary>
    public static class ViewModelFactory
    {
        /// <summary>
        /// Singleton's Storage.
        /// </summary>
        private static Dictionary<Type, ViewModelBase> _singletons;

        /// <summary>
        /// StaticConstructor: Needed to instanciate private members.
        /// </summary>
        static ViewModelFactory()
        {
            _singletons = new Dictionary<Type, ViewModelBase>();
        }

        /// <summary>
        /// Give back a new instance of a ViewModel.
        /// </summary>
        /// <typeparam name="TViewModel">The expected ViewModel's type.</typeparam>
        /// <returns>A new instance of a ViewModel.</returns>
        public static TViewModel New<TViewModel>() where TViewModel : ViewModelBase, new()
        {
            return new TViewModel();
        }

        /// <summary>
        /// At first call, give a new instance of a ViewModel.
        /// Any other calls will give the same instance.
        /// WARNING: If called after a "New" command, will not give that instance.
        /// </summary>
        /// <typeparam name="TViewModel">The expected ViewModel's type.</typeparam>
        /// <returns>At first call, give a new instance of a ViewModel. Any other calls give the same instance.</returns>
        public static TViewModel GetInstance<TViewModel>() where TViewModel : ViewModelBase, new()
        {
            Type vmType = typeof(TViewModel);

            if (!_singletons.ContainsKey(vmType))
                _singletons.Add(vmType, New<TViewModel>());

            return _singletons[vmType] as TViewModel;
        }
    }
}
